<template>
  <div class="team-collaboration-page">
    <!-- 页面头部 -->
    <div class="page-header">
      <h2 class="page-title">四员协同</h2>
      <el-button 
        type="primary" 
        size="small" 
        @click="refreshData"
        :loading="loading"
        :icon="Refresh"
      >
        刷新
      </el-button>
    </div>

    <!-- 服务说明 -->
    <div class="service-info">
      <div class="info-header">
        <el-icon class="info-icon"><InfoFilled /></el-icon>
        <span class="info-title">服务说明</span>
      </div>
      <div class="info-content">
        记录与专卖、物流、内管的协同工作情况
      </div>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-cards">
      <div class="stats-card main-card" @click="goToDetail" :class="{ 'from-reminder': isFromTaskReminder }">
        <div class="card-header">
          <div class="card-title">
            <el-icon class="title-icon"><UserFilled /></el-icon>
            四员协同完成情况
            <el-tag v-if="isFromTaskReminder && !isCompleted" type="warning" size="small">需要完成</el-tag>
          </div>
          <el-icon class="arrow-icon"><ArrowRight /></el-icon>
        </div>
        <div class="card-content">
          <div class="completion-status">
            <div class="status-icon" :class="{ 'completed': isCompleted }">
              <el-icon v-if="isCompleted"><Check /></el-icon>
              <el-icon v-else><Warning /></el-icon>
            </div>
            <div class="status-text">
              <div class="status-title">{{ isCompleted ? '本月已完成' : '本月未完成' }}</div>
              <div class="status-desc">{{ statusDescription }}</div>
              <div v-if="isFromTaskReminder && !isCompleted" class="reminder-hint">点击即可添加记录</div>
            </div>
          </div>
        </div>
      </div>

      <!-- 月度进度卡片 -->
      <div class="stats-card month-card">
        <div class="card-title">
          <el-icon class="title-icon"><Calendar /></el-icon>
          本月进度
        </div>
        <div class="month-info">
          <div class="month-item">
            <span class="month-label">当前月份</span>
            <span class="month-value">{{ currentMonth }}月</span>
          </div>
          <div class="month-item">
            <span class="month-label">提交要求</span>
            <span class="month-value">{{ getSubmissionRequirement() }}</span>
          </div>
          <div class="month-item">
            <span class="month-label">剩余天数</span>
            <span class="month-value" :class="{ 'urgent': remainingDays <= 3 }">
              {{ remainingDays }}天
            </span>
          </div>
        </div>
      </div>
    </div>

    <!-- 快速操作 -->
    <div class="quick-actions">
      <div class="action-title">快速操作</div>
      <div class="action-buttons">
        <el-button 
          class="action-btn"
          @click="goToDetail"
        >
          <el-icon><Document /></el-icon>
          查看记录
        </el-button>
        <el-button 
          class="action-btn"
          @click="showAddRecordDialog = true"
          :disabled="isCompleted"
        >
          <el-icon><Plus /></el-icon>
          {{ isCompleted ? '已完成' : '添加记录' }}
        </el-button>
      </div>
    </div>

    <!-- 本月记录 -->
    <div class="current-record" v-if="currentMonthRecords.length > 0">
      <div class="section-header">
        <h3>本月协同记录 ({{ currentMonthRecords.length }}条)</h3>
        <el-tag :type="isCompleted ? 'success' : 'info'" size="small">
          {{ isCompleted ? '已完成' : '进行中' }}
        </el-tag>
      </div>
      
      <div 
        v-for="record in currentMonthRecords" 
        :key="record.id"
        class="record-card"
        style="margin-bottom: 12px;"
      >
        <div class="record-header">
          <div class="record-date">{{ formatDate(record.completionDate) }}</div>
          <el-button 
            size="small" 
            text 
            type="primary"
            @click="editRecord(record)"
          >
            编辑
          </el-button>
        </div>
        <div class="record-content">
          <div class="record-notes">{{ record.notes || '暂无详细记录' }}</div>
        </div>
      </div>
    </div>

    <!-- 历史记录 -->
    <div class="history-records" v-if="historyRecords.length > 0">
      <div class="section-header">
        <h3>历史记录</h3>
        <el-button 
          type="primary" 
          text 
          size="small"
          @click="goToDetail"
        >
          查看更多
        </el-button>
      </div>
      
      <div class="record-list">
        <div 
          v-for="record in historyRecords.slice(0, 3)" 
          :key="record.id"
          class="history-item"
        >
          <div class="history-date">{{ formatMonthDate(record.completionDate) }}</div>
          <div class="history-content">{{ record.notes || '暂无详细记录' }}</div>
        </div>
      </div>
    </div>

    <!-- 提醒信息 -->
    <div class="reminder-card" v-if="shouldShowReminder">
      <div class="reminder-header">
        <el-icon class="reminder-icon"><Bell /></el-icon>
        <span class="reminder-title">任务提醒</span>
      </div>
      <div class="reminder-content">
        {{ getReminderMessage() }}
      </div>
      <div class="reminder-actions">
        <el-button size="small" type="primary" @click="showAddRecordDialog = true">
          立即添加
        </el-button>
      </div>
    </div>

    <!-- 添加协同记录对话框 -->
    <el-dialog
      v-model="showAddRecordDialog"
      title="添加四员协同记录"
      width="90%"
    >
      <el-form :model="recordForm" label-position="top">
        <el-form-item label="协同日期">
          <el-date-picker
            v-model="recordForm.collaborationDate"
            type="date"
            placeholder="选择协同日期"
            style="width: 100%"
            :disabled-date="disabledDate"
          />
        </el-form-item>

        <el-form-item label="相关客户" required>
          <el-select
            v-model="recordForm.clientId"
            filterable
            remote
            reserve-keyword
            placeholder="搜索选择客户"
            :remote-method="searchClients"
            :loading="loading"
            style="width: 100%"
            @focus="searchClients('')"
          >
            <el-option
              v-for="client in clientSearchResults"
              :key="client.id"
              :label="`${client.clientName} (${client.clientCode})`"
              :value="client.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="协同内容" required>
          <el-input
            v-model="recordForm.notes"
            type="textarea"
            :rows="6"
            placeholder="记录与专卖物流内管的协同工作情况"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="showAddRecordDialog = false">取消</el-button>
        <el-button 
          type="primary" 
          @click="submitRecord"
          :loading="submitting"
          :disabled="!recordForm.collaborationDate || !recordForm.clientId || !recordForm.notes.trim()"
        >
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import {
  UserFilled,
  ArrowRight,
  Calendar,
  Check,
  Warning,
  Document,
  Plus,
  Bell,
  Refresh,
  InfoFilled
} from '@element-plus/icons-vue'
import { trpc } from '@/utils/trpc'
import { AuthUtils } from '@/utils/auth'

const router = useRouter()
const route = useRoute()

// 响应式数据
const loading = ref(false)
const submitting = ref(false)
const currentMonthRecord = ref(null)
const currentMonthRecords = ref([]) // 本月所有记录
const historyRecords = ref([])
const showAddRecordDialog = ref(false)
const teamService = ref(null)

// 表单数据
const recordForm = ref({
  collaborationDate: null,
  clientId: null,
  notes: ''
})

// 客户搜索相关
const clientSearchKeyword = ref('')
const clientSearchResults = ref([])
const showClientDropdown = ref(false)

// 计算属性
const isCompleted = computed(() => {
  if (!teamService.value) return false
  const requiredCount = teamService.value.cycleValue || 1
  return currentMonthRecords.value.length >= requiredCount
})

const statusDescription = computed(() => {
  if (!teamService.value) return '加载中...'
  
  const requiredCount = teamService.value.cycleValue || 1
  const completedCount = currentMonthRecords.value.length
  
  if (isCompleted.value) {
    const latestRecord = currentMonthRecords.value[0]
    return `本月已完成 ${completedCount}/${requiredCount} 条记录`
  }
  
  const remainingCount = requiredCount - completedCount
  return `本月还需提交${remainingCount}条协同记录`
})

const shouldShowReminder = computed(() => {
  return !isCompleted.value && remainingDays.value <= 7
})

const isFromTaskReminder = computed(() => {
  return route.query.filter === 'uncompleted'
})

const currentMonth = computed(() => {
  return new Date().getMonth() + 1
})

const remainingDays = computed(() => {
  const today = new Date()
  const endOfMonth = new Date(today.getFullYear(), today.getMonth() + 1, 0)
  const diffTime = endOfMonth.getTime() - today.getTime()
  return Math.ceil(diffTime / (1000 * 60 * 60 * 24))
})

// 方法
const loadData = async () => {
  try {
    loading.value = true
    const managerId = getCurrentManagerId()
    if (!managerId) return

    // 获取四员协同服务的ID（从服务列表中查找"四员协同"）
    const serviceList = await trpc.service.list.query({ pageSize: 100 })
    if (!serviceList?.success) throw new Error('加载服务列表失败')
    const services = serviceList.data.data || serviceList.data || []
    const foundService = services.find((s: any) => s.serviceName?.includes('四员协同'))
    const teamServiceId = foundService?.id

    if (!teamServiceId || !foundService) {
      console.warn('未找到四员协同服务')
      currentMonthRecord.value = null
      historyRecords.value = []
      teamService.value = null
      return
    }

    // 保存服务信息到响应式变量
    teamService.value = foundService

    // 计算本月时间范围
    const { startDate, endDate } = getCurrentMonthRange()

    const result = await trpc.workLog.serviceStats.query({
      managerId,
      serviceId: teamServiceId,
      startDate: startDate.toISOString(),
      endDate: endDate.toISOString()
    })

    if (result.success) {
      const recentLogs = result.data.recentLogs || []
      
      // 查找本月记录
      const thisMonth = new Date().getMonth()
      const thisYear = new Date().getFullYear()
      
      // 本月所有记录
      currentMonthRecords.value = recentLogs.filter(log => {
        const logDate = new Date(log.completionDate)
        return logDate.getMonth() === thisMonth && logDate.getFullYear() === thisYear
      })

      // 最新的一条本月记录（用于显示）
      currentMonthRecord.value = currentMonthRecords.value.length > 0 ? currentMonthRecords.value[0] : null

      // 历史记录（排除本月）
      historyRecords.value = recentLogs.filter(log => {
        const logDate = new Date(log.completionDate)
        return !(logDate.getMonth() === thisMonth && logDate.getFullYear() === thisYear)
      })
    }
  } catch (error) {
    console.error('加载四员协同数据失败:', error)
    ElMessage.error('加载数据失败')
  } finally {
    loading.value = false
  }
}

const getCurrentMonthRange = () => {
  const now = new Date()
  const startDate = new Date(now.getFullYear(), now.getMonth(), 1)
  const endDate = new Date(now.getFullYear(), now.getMonth() + 1, 0)
  return { startDate, endDate }
}

const refreshData = () => {
  loadData()
}

const goToDetail = () => {
  // 如果是从任务提醒跳转过来且未完成，显示添加记录对话框
  const fromTaskReminder = route.query.filter === 'uncompleted'
  if (fromTaskReminder && !isCompleted.value) {
    showAddRecordDialog.value = true
    return
  }
  
  // 否则跳转到详情页面
  router.push({
    name: 'TeamCollaborationDetail',
    query: { 
      period: 'month'
    }
  })
}

const formatDate = (dateStr: string) => {
  // 解析日期字符串，避免时区问题
  if (dateStr.includes('T')) {
    // 如果是完整的ISO日期时间字符串，直接使用Date构造函数
    const date = new Date(dateStr)
    return `${date.getMonth() + 1}月${date.getDate()}日`
  } else {
    // 如果是纯日期字符串，手动解析避免时区问题
    const [year, month, day] = dateStr.split('-').map(Number)
    return `${month}月${day}日`
  }
}

const formatMonthDate = (dateStr: string) => {
  const date = new Date(dateStr)
  return `${date.getFullYear()}年${date.getMonth() + 1}月`
}

const getReminderMessage = () => {
  if (!teamService.value) return '请及时记录协同工作情况。'
  
  const requiredCount = teamService.value.cycleValue || 1
  const completedCount = currentMonthRecords.value.length
  const remainingCount = requiredCount - completedCount
  
  if (remainingDays.value <= 3) {
    return `本月四员协同记录即将截止，还有${remainingDays.value}天！还需提交${remainingCount}条记录。`
  }
  return `本月还需提交${remainingCount}条四员协同记录，请及时记录协同工作情况。`
}

const editRecord = (record: any) => {
  recordForm.value = {
    collaborationDate: new Date(record.completionDate),
    clientId: record.clientId || null,
    notes: record.notes || ''
  }
  showAddRecordDialog.value = true
}

const disabledDate = (time: Date) => {
  // 只能选择本月的日期
  const today = new Date()
  const thisMonth = today.getMonth()
  const thisYear = today.getFullYear()
  const timeMonth = time.getMonth()
  const timeYear = time.getFullYear()
  
  return timeYear !== thisYear || timeMonth !== thisMonth || time.getTime() > Date.now()
}

const submitRecord = async () => {
  if (!recordForm.value.collaborationDate || !recordForm.value.notes.trim()) return

  submitting.value = true
  try {
    const managerId = getCurrentManagerId()
    if (!managerId) return

    // 获取四员协同服务的ID（从服务列表中查找"四员协同"）
    const serviceList = await trpc.service.list.query({ pageSize: 100 })
    if (!serviceList?.success) throw new Error('加载服务列表失败')
    const services = serviceList.data.data || serviceList.data || []
    const foundService = services.find((s: any) => s.serviceName?.includes('四员协同'))
    const teamServiceId = foundService?.id

    if (!teamServiceId) {
      ElMessage.error('未找到四员协同服务')
      return
    }

    // 为了避免重复记录检查，给四员协同记录添加时间戳使其唯一
    const completionDate = new Date(recordForm.value.collaborationDate)
    // 添加当前时间的时分秒，确保同一天可以有多条记录
    const now = new Date()
    completionDate.setHours(now.getHours(), now.getMinutes(), now.getSeconds(), now.getMilliseconds())

    // 创建新记录，使用用户选择的客户ID
    const result = await trpc.workLog.create.mutate({
      managerId,
      clientId: recordForm.value.clientId,
      serviceId: teamServiceId,
      completionDate: completionDate.toISOString(),
      notes: recordForm.value.notes.trim()
    })

    if (result.success) {
      ElMessage.success('四员协同记录提交成功')
      showAddRecordDialog.value = false
      recordForm.value = {
        collaborationDate: null,
        clientId: null,
        notes: ''
      }
      await loadData()
    } else {
      ElMessage.error(result.message || '提交记录失败')
    }
  } catch (error) {
    console.error('提交协同记录失败:', error)
    ElMessage.error('提交记录失败')
  } finally {
    submitting.value = false
  }
}

const getCurrentManagerId = () => {
  const user = AuthUtils.getUser<any>()
  return user?.id || null
}

// 客户搜索方法
const searchClients = async (keyword: string) => {
  try {
    const managerId = getCurrentManagerId()
    if (!managerId) return

    // 如果没有关键词，获取一些默认客户
    if (!keyword.trim()) {
      keyword = ''
    }

    const result = await trpc.workLog.searchClients.query({
      managerId,
      keyword: keyword.trim() || ' ', // 空格表示搜索所有
      serviceId: teamService.value?.id
    })

    if (result.success) {
      clientSearchResults.value = result.data || []
    }
  } catch (error) {
    console.error('搜索客户失败:', error)
  }
}

const getSubmissionRequirement = () => {
  if (!teamService.value) return '每月1条记录'
  
  const { completionCycle, cycleValue = 1 } = teamService.value
  
  switch (completionCycle) {
    case 'daily':
      return cycleValue === 1 ? '每日1条记录' : `每日${cycleValue}条记录`
    case 'weekly':
      return cycleValue === 1 ? '每周1条记录' : `每周${cycleValue}条记录`
    case 'monthly':
      return cycleValue === 1 ? '每月1条记录' : `每月${cycleValue}条记录`
    case 'quarterly':
      return cycleValue === 1 ? '每季度1条记录' : `每季度${cycleValue}条记录`
    case 'yearly':
      return cycleValue === 1 ? '每年1条记录' : `每年${cycleValue}条记录`
    default:
      return '每月1条记录'
  }
}

// 生命周期
onMounted(() => {
  loadData()
  
  // 处理不同来源的跳转
  const fromTaskReminder = route.query.filter === 'uncompleted'
  const fromDetailPage = route.query.action === 'add'
  
  if (fromTaskReminder) {
    // 从任务提醒跳转：等待数据加载完成后再检查是否未完成
    setTimeout(() => {
      if (!isCompleted.value) {
        showAddRecordDialog.value = true
      }
    }, 500)
  } else if (fromDetailPage) {
    // 从详情页面跳转：直接打开添加对话框
    setTimeout(() => {
      showAddRecordDialog.value = true
    }, 500)
  }
})
</script>

<style scoped>
.team-collaboration-page {
  background: #f5f7fa;
  min-height: 100vh;
  padding-bottom: 20px;
}

.page-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px 20px;
  background: white;
  border-bottom: 1px solid #ebeef5;
}

.page-title {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
}

.service-info {
  background: #f0f5ff;
  border: 1px solid #adc6ff;
  margin: 12px;
  border-radius: 8px;
  padding: 16px;
}

.info-header {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.info-icon {
  color: #597ef7;
  margin-right: 8px;
}

.info-title {
  font-size: 14px;
  font-weight: 600;
  color: #597ef7;
}

.info-content {
  font-size: 13px;
  color: #1d39c4;
  line-height: 1.4;
}

.stats-cards {
  padding: 12px;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.stats-card {
  background: white;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
}

.main-card {
  cursor: pointer;
  transition: transform 0.2s;
}

.main-card:active {
  transform: scale(0.98);
}

.main-card.from-reminder {
  border: 2px solid #e6a23c;
  box-shadow: 0 2px 12px rgba(230, 162, 60, 0.15);
}

.main-card.from-reminder:hover {
  box-shadow: 0 4px 20px rgba(230, 162, 60, 0.25);
}

.reminder-hint {
  color: #e6a23c;
  font-size: 12px;
  margin-top: 4px;
  font-weight: 500;
}

.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 16px;
}

.card-title {
  display: flex;
  align-items: center;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.title-icon {
  margin-right: 8px;
  color: #409eff;
}

.arrow-icon {
  color: #c0c4cc;
}

.completion-status {
  display: flex;
  align-items: center;
  gap: 16px;
}

.status-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f56c6c;
  color: white;
  font-size: 24px;
}

.status-icon.completed {
  background: #67c23a;
}

.status-text {
  flex: 1;
}

.status-title {
  font-size: 18px;
  font-weight: 600;
  margin-bottom: 4px;
}

.status-desc {
  font-size: 14px;
  color: #909399;
}

.month-card .card-title {
  margin-bottom: 16px;
}

.month-info {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.month-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 12px;
  background: #f5f7fa;
  border-radius: 6px;
}

.month-label {
  font-size: 14px;
  color: #606266;
}

.month-value {
  font-size: 14px;
  font-weight: 600;
  color: #409eff;
}

.month-value.urgent {
  color: #f56c6c;
}

.quick-actions {
  margin: 12px;
  background: white;
  border-radius: 12px;
  padding: 20px;
}

.action-title {
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 16px;
}

.action-buttons {
  display: flex;
  gap: 12px;
}

.action-btn {
  flex: 1;
  height: 44px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 4px;
  border: 1px solid #dcdfe6;
  background: white;
  color: #606266;
}

.action-btn:hover:not(:disabled) {
  border-color: #409eff;
  color: #409eff;
}

.action-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.current-record,
.history-records {
  margin: 12px;
  background: white;
  border-radius: 12px;
  padding: 20px;
}

.section-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 16px;
}

.section-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
}

.record-card {
  background: #f5f7fa;
  border-radius: 8px;
  padding: 16px;
}

.record-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 12px;
}

.record-date {
  font-size: 14px;
  font-weight: 600;
  color: #409eff;
}

.record-content {
  line-height: 1.5;
}

.record-notes {
  font-size: 14px;
  color: #606266;
}

.record-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.history-item {
  display: flex;
  gap: 12px;
  padding: 12px;
  background: #f5f7fa;
  border-radius: 8px;
}

.history-date {
  font-size: 12px;
  color: #909399;
  white-space: nowrap;
  min-width: 60px;
}

.history-content {
  font-size: 13px;
  color: #606266;
  flex: 1;
  line-height: 1.4;
}

.reminder-card {
  margin: 12px;
  background: linear-gradient(135deg, #f0f5ff 0%, #e6f0ff 100%);
  border: 1px solid #adc6ff;
  border-radius: 12px;
  padding: 16px;
}

.reminder-header {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.reminder-icon {
  color: #597ef7;
  margin-right: 8px;
}

.reminder-title {
  font-size: 14px;
  font-weight: 600;
  color: #1d39c4;
}

.reminder-content {
  font-size: 13px;
  color: #10239e;
  margin-bottom: 12px;
  line-height: 1.4;
}

.reminder-actions {
  display: flex;
  justify-content: flex-end;
}

:deep(.el-dialog) {
  margin-top: 5vh;
}

:deep(.el-dialog__body) {
  padding: 20px;
}
</style>
